<template>
    <el-button plain :disabled="props.disabled" @click="onShow">创建链接</el-button>
    <el-dialog
        v-model="show"
        class="select-already-dialog"
        title="创建链接"
        width="670px"
        :before-close="onClose"
        append-to-body>
        <el-scrollbar max-height="600px" style="padding-right: 20px">
            <el-form ref="formRef" class="form_link" :model="formInfo" :rules="rules" label-width="100px">
                <!-- 标题 -->
                <el-form-item label="链接标题" prop="link_title">
                    <el-input
                        v-model="formInfo.link_title"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入链接标题"></el-input>
                </el-form-item>
                <!-- 链接地址 -->
                <el-form-item label="链接地址" prop="link_url">
                    <el-input v-model="formInfo.link_url" type="text" placeholder="请输入链接地址"></el-input>
                </el-form-item>
                <!-- 连接描述 -->
                <el-form-item label="链接描述" prop="link_desc">
                    <el-input
                        v-model="formInfo.link_desc"
                        type="textarea"
                        :rows="2"
                        maxlength="50"
                        show-word-limit
                        placeholder="请输入链接描述"></el-input>
                </el-form-item>
                <el-form-item label="链接封面" prop="link_share_image">
                    <el-upload
                        ref="uploadFileRef"
                        v-loading="upLoadLoading"
                        class="share-img-uploader"
                        action=""
                        accept=".jpg,.JPG,.jpeg,.JPEG,.png,.PNG"
                        :multiple="false"
                        :show-file-list="false"
                        :before-upload="onBeforeUpload"
                        :http-request="onUploadFile">
                        <template #default>
                            <div v-if="formInfo.link_share_image" class="share-img-uploader-img">
                                <img :src="formInfo.link_share_image" />
                                <div class="uploader-img-hover" @click.stop>
                                    <el-icon class="upload-icon" @click="onPreview"><ZoomIn /></el-icon>
                                    <el-icon class="upload-icon" @click="onDel"><Delete /></el-icon>
                                </div>
                            </div>

                            <el-icon v-else class="share-img-uploader-icon"><Plus /></el-icon>
                        </template>
                        <template #tip>
                            <div class="upload-tip">图片支持png；jpg；jpeg格式，大小2M以内，建议尺寸200*200px。</div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
            <div class="footer-box">
                <el-button plain @click="onClose">取消</el-button>
                <el-button class="ml20" type="primary" @click="onSave"> 保存 </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="preViewImgShow" append-to-body>
        <img class="preview-img" :src="formInfo.link_share_image" alt="" />
    </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref, reactive, computed, watch, withDefaults, getCurrentInstance } from 'vue';
import { getImageWH } from '../../utils/index';
import { uploadFileApi } from '../../api/material';

interface Props {
    /** 是否禁用 */
    disabled: boolean;
}

const props = withDefaults(defineProps<Props>(), {
    disabled: false
});

const emit = defineEmits(['submit']);

const show = ref<boolean>(false);

const preViewImgShow = ref<boolean>(false);

const upLoadLoading = ref<boolean>(false);

const formRef = ref();

const app = getCurrentInstance();

const formInfo = reactive({
    id: 0,
    link_title: '',
    link_url: '',
    link_desc: '',
    link_share_image: '',
    code: ''
});

const validateHttp = (rule, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入订阅URL'));
    } else {
        const reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
        if (reg.test(value)) {
            callback();
        } else {
            callback(new Error('请输入带有http或https的正确URL'));
        }
    }
};

const rules = reactive({
    link_title: [
        {
            required: true,
            message: '链接标题不能为空',
            trigger: 'blur'
        }
    ],
    link_url: [
        {
            required: true,
            message: '链接地址不能为空',
            trigger: 'blur'
        },
        { validator: validateHttp, trigger: 'blur' }
    ],
    link_share_image: [
        {
            required: true,
            message: '链接封面不能为空',
            trigger: 'change'
        }
    ]
});

/**
 * 文件上传之前处理
 */
const onBeforeUpload = async (file: any) => {
    const accept = '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG';
    const isMB = file.size / 1024 / 1024 <= 2;

    if (!isMB) {
        ElMessage.warning(`上传的文件最大支持2M`);
        return false;
    }
    const fileType = file?.name?.substring(file?.name?.lastIndexOf('.'));
    if (accept.indexOf(fileType) == -1) {
        ElMessage.error(`文件格式不正确，请上传图片格式文件！`);
        return false;
    }
    return true;
};

/**
 * 文件上传
 */
const onUploadFile = async ({ file }: any) => {
    upLoadLoading.value = true;
    const params = {
        file: file,
        fileName: file.name
    };
    const res = await uploadFileApi(app, params);

    formInfo.link_share_image = res?.url || '';
    formInfo.code = res?.code || '';
    upLoadLoading.value = false;
};

const onShow = () => {
    show.value = true;
};

/**
 * 图片预览
 */
const onPreview = () => {
    preViewImgShow.value = true;
};

/**
 * 图片删除
 */
const onDel = () => {
    formInfo.link_share_image = '';
};

/**
 * 关闭/取消
 */
const onClose = () => {
    formRef.value.resetFields();
    formInfo.link_title = '';
    formInfo.link_url = '';
    formInfo.link_desc = '';
    formInfo.link_share_image = '';
    formInfo.code = '';
    show.value = false;
};

/**
 * 保存
 */
const onSave = async () => {
    formRef.value?.validate(res => {
        if (res) {
            const info = {
                type: 3,
                is_local: true,
                title: formInfo.link_title,
                content: formInfo.link_desc,
                cover_image_url: formInfo.link_share_image,
                code: formInfo.code,
                link_url: formInfo.link_url,
                link_desc: formInfo.link_desc,
                sortTime: +new Date()
            };
            emit('submit', info);
            show.value = false;
        }
    });
};
</script>
<style lang="scss" scoped>
.el-form.form_link {
    margin: 10px;

    .el-form-item {
        margin-bottom: 18px !important;
    }
}

:deep .el-scrollbar {
    height: 50%;
}

.share-img-uploader {
    :deep(.el-upload) {
        border: 1px dashed #dcdfe6;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    :deep(.el-upload:hover) {
        border-color: var(--el-color-primary);
    }

    .upload-tip {
        font-size: 12px;
    }
}

.el-icon.share-img-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 110px;
    height: 110px;
    text-align: center;
}

.share-img-uploader-img {
    width: 110px;
    height: 110px;
    position: relative;

    img {
        width: 100%;
        height: 100%;
    }

    .uploader-img-hover {
        position: absolute;
        inset: 0;
        background: rgb(0 0 0 / 40%);
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;

        .upload-icon {
            width: 40px;
            color: #fff;
            font-size: 24px;
        }
    }

    .uploader-img-hover:hover {
        opacity: 1;
    }
}

.preview-img {
    width: 100%;
}
</style>
